import config from '../../assets/project.config.json'
import { DLine } from '../draw-obj/DLine';
import { DPoint } from '../draw-obj/DPoint';
import type { JsonLine } from './json-obj/JsonLine';
import type { JsonPoint } from './json-obj/JsonPoint';
import NormalLineMapping from './mapping-template/NormalLineMapping.json';
import PointMapping from './mapping-template/PointMapping.json';

export class JsonParser {

  private lineFieldMapping: object
  private pointFieldMapping: object

  private lineItem: DLine[] = [];
  constructor() {
    this.lineFieldMapping = NormalLineMapping;
    this.pointFieldMapping = PointMapping;
  }
  init() {
    console.log(config);


  }

  startParserJson(jsonData: object) {
    this.lineItem = [];
    this.parserJsonData(jsonData, []);

    console.log(this.lineItem);
  }

  parserJsonData(jsonObj: object, path: string[]) {
    
    if (Array.isArray(jsonObj)) {
      const nowPathItem = "Array"
      jsonObj.forEach((item, index) => {
        this.parserJsonData(item, [...path, "ArrayItem " + index + ":" ])
      });

    } 
    else if (jsonObj !== null && typeof jsonObj === 'object') {
      const objEntries = Object.entries(jsonObj);

      const name = this.getName(objEntries);
      if (name) {
        path.push("(" + name + ")")
      }

      const entity = this.checkObj(jsonObj, path);
      if (entity) {
        entity.path = path.join("");
        this.lineItem.push(entity);
      }

      objEntries.forEach(([key, value]) => {
        this.parserJsonData(value, [...path, key + ">"]);
      });
    }
  }

  getName(objEntries: [string, any][]) {
    return objEntries.find(([key]) => {
      return key === "Name"
    })?.[1];
  }

  checkObj(jsonObj: object, path: string[]) {
    let entity: any = null;
    
    // 检查是否为线对象
    if (this.checkLine(jsonObj)) {
      entity = this.convertDLine(jsonObj as JsonLine);
      console.log("---")
      console.log(entity);
      console.log(path.join(""));
    }

    return entity
  }

  checkLine(jsonObj: object) {
    const keys = Object.keys(jsonObj);
    const index = keys.findIndex((key) => {
      return key === "LineType";
    })

    return index > -1;
  }

  convertDLine(jsonObj: JsonLine): DLine { 
    let line = new DLine();

    line.startPoint = this.converDPoint(jsonObj.StartP);
    line.endPoint = this.converDPoint(jsonObj.EndP);
    line.midPoint = this.converDPoint(jsonObj.MidP);
    line.centerPoint  = this.converDPoint(jsonObj.CenterP);
    line.lineType = jsonObj.LineType;
    line.arcDirect = jsonObj.ArcDirect;
    line.arcHeight = jsonObj.ArcHeight;
    line.r = jsonObj.R;

    return line;
  }

  converDPoint(jsonObj: JsonPoint): DPoint {
    let point = new DPoint(0, 0);

    point.x = jsonObj.X;
    point.y = jsonObj.Y;

    return point;

  }


}






type JsonParserConfig = {
  lineFieldMapping: any,
  lineMatchName: string[]
}